import prisma from "../prisma/prismaClient.js";

// 创建下载记录
const createDownload = (fileId, ip, userAgent) => {
    return prisma.download.create({
        data: {
            fileId,
            ip,
            userAgent,
        },
    });
}

const getDownloadById = (downloadId) => {
    return prisma.download.findUnique({
        where: { id: downloadId },
        include: {
            file: true,
        }
    });
}

//获取下载总数和下载新增数
const getDownloadIncreaseInfo = async () => {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);

    const total = await prisma.download.count()
    const today = await prisma.download.count({
        where: {
            createdAt: {
                gte: todayStart,
            }
        }
    })
    return {
        total,
        today
    }
}

//获取最近几天的下载量
const getRecentDaysDownloads = async (days = 7) => {
    const results = [];
    const today = new Date();

    for (let i = days - 1; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(date.getDate() - i);

        const startOfDay = new Date(date);
        startOfDay.setHours(0, 0, 0, 0);

        const endOfDay = new Date(date);
        endOfDay.setHours(23, 59, 59, 999);

        const count = await prisma.download.count({
            where: {
                createdAt: {
                    gte: startOfDay,
                    lte: endOfDay
                },
            },
        });

        results.push({
            date: date.toISOString().split('T')[0],
            count,
        })
    }

    return results;
}


const getDownloads = () => {
    return prisma.download.findMany({
        include: {
            file: true,
        },
    })
}

export default {
    createDownload,
    getDownloadById,
    getDownloadIncreaseInfo,
    getDownloads,
    getRecentDaysDownloads
}
